package com.typhoon.extend.dao;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.google.common.collect.Lists;
import com.typhoon.extend.dto.request.QueryRoleReq;
import com.typhoon.extend.entity.Role;

@Repository("roleDao")
public class RoleDao extends BaseDao {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(RoleDao.class);
	
	private static final String TABLE_ROLE = "Role";
	
	@Resource
	private JdbcTemplate extendJdbc;

	public CountAndResult<Role> queryPageByCondition(QueryRoleReq req, int offset, int pageSize) {
		StringBuilder sql = new StringBuilder();
		StringBuilder countSql = new StringBuilder();
		StringBuilder where = new StringBuilder();
		List<Object> paramList = Lists.newArrayList();
		
		sql.append(select).append(star);
		countSql.append(select).append("	count(1)	");
		
		where.append(from);
		where.append(TABLE_ROLE);
		where.append(" where ");
		where.append(oneEqOne);
		if(null != req.getRoleName()) {
			where.append(and).append("	roleName = ?	");
			paramList.add(req.getRoleName());
		}
		countSql.append(where);
		sql.append(where).append("	ORDER BY createTime DESC LIMIT ?,?	");
		try {
			int count = this.extendJdbc.queryForObject(countSql.toString(),paramList.toArray(),Integer.class);
			if(count <= 0) {
				return null;
			}
			paramList.add(offset);
			paramList.add(pageSize);
			List<Role> list = this.extendJdbc.query(sql.toString(),paramList.toArray(),BeanPropertyRowMapper.newInstance(Role.class));
			return new CountAndResult<>(count, list);
		} catch (Exception e) {
			LOGGER.error("查询角色信息异常",e);
			return null;
		}
	}

	public List<Role> listAllByUserId(Long userId) {
		StringBuilder sql = new StringBuilder();
		sql.append("	SELECT	");
		sql.append("		r.*	");
		sql.append("	FROM	");
		sql.append("		Role r	");
		sql.append("	LEFT JOIN UserOfRole uor ON r.id = uor.roleId	");
		sql.append("	WHERE	");
		sql.append("		uor.userId = ?	");
		return this.extendJdbc.query(sql.toString(), BeanPropertyRowMapper.newInstance(Role.class), userId);

	}
	
	

}
